<?php
/**
 * @title 187. 重复的DNA序列 - 哈希+位运算
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param String $s
     * @return String[]
     */
    function findRepeatedDnaSequences($s) {
        /**
         * @since 2021-10-08 字符串长度
         */
        $len = strlen($s);
        if($len < 10){
            return [];
        } else {}

        /**
         * @since 2021-10-08 对应二进制
         */
        $charArray = [
            "A" => 0,
            "C" => 1,
            "G" => 2,
            "T" => 3,
        ];

        /**
         * @since 2021-10-08 结果集
         */
        $result = [];

        /**
         * @since 2021-10-09 第一个组合
         */
        $num = 0;
        $word = "";
        for ($i=0; $i<10; $i++){
            $num = ($num<<2) + $charArray[$s[$i]];
            $word = $word . $s[$i];
        }
        // echo "num={$num}, num_bin=", decbin($num), PHP_EOL;

        /**
         * @since 2021-10-08 哈希数组
         */
        $hashArray = [$num => 1];

        /**
         * @since 2021-10-08 迭代
         */
        for(; $i<$len; $i++){
            /**
             * @since 2021-10-09 去除前2位, bindec(18个1) = 2^18-1=262143
             */
            $num = $num & 262143;
            $num = ($num<<2) + $charArray[$s[$i]];
            $word = substr($word . $s[$i], -10);
            // echo "char=", $s[$i] ,", num={$num}, num_bin=", decbin($num), PHP_EOL;

            /**
             * @since 2021-10-08 判断出现次数
             */
            if(isset($hashArray[$num])){
                $hashArray[$num] += 1;
                if($hashArray[$num] == 2){
                    $result[] = $word;
                } else {}
            } else {
                $hashArray[$num] = 1;
            }
        }

        /**
         * @return
         */
        return $result;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202008/2020.08.11_10.php
 */
$datas = [
    "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->findRepeatedDnaSequences($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
